package com.experient.test.api;

import android.accounts.NetworkErrorException;
import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

/**
 * 封装的请求类
 */
public class UrlRequest {

    public static JSONObject post(String url, Map<String, String> params) throws NetworkErrorException {
        HttpURLConnection connection = null;
        try {
            URL requestUrl = new URL(url);
            connection = (HttpURLConnection) requestUrl.openConnection();


            //设置请求参数
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(5000);

            //转化参数
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
            sb.deleteCharAt(sb.length() - 1);

            //使用流进行访问
            connection.getOutputStream().write(sb.toString().getBytes());
            connection.getOutputStream().flush();
            connection.getOutputStream().close();

            int responseCode = connection.getResponseCode();

            //如果访问成功
            if (responseCode == HttpURLConnection.HTTP_OK) {

                //获取输入流
                InputStream inputStream = connection.getInputStream();

                //转化为字符串
                StringBuilder sb2 = new StringBuilder();
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = inputStream.read(buffer)) != -1) {
                    sb2.append(new String(buffer, 0, len));
                }
                inputStream.close();

                JSONObject jsonObject = new JSONObject(sb2.toString());


                //返回结果
                return jsonObject;

            }else {
                Log.e("UrlRequest", "请求失败，错误码：" + responseCode);

                throw new NetworkErrorException("请求失败，错误码：" + responseCode);
            }

        }catch (Exception e){
            e.printStackTrace();
            Log.e("UrlRequest失败", "post: "+e.getMessage());
            throw new NetworkErrorException("请求失败，错误码：" + e.getMessage());
        }

    }

}
